#include"offlinemessagemodel.hpp"
#include"CommonConnectionPool.hpp"

//插入用户的离线消息
bool OfflineMsgModel::insertMsg(int userid,string msg){
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into OfflineMessage values(%d, '%s')",
            userid,
            msg.c_str()       
            );

    // 从连接池中获取一个mysql连接
    ConnectionPool *sqlConnPool = ConnectionPool::getConnectionPool();
    auto sqlConn = sqlConnPool->getConnection();

    // 执行操作
    bool state = sqlConn->update(sql);
    if (state)
    {
        return true;
    }
    return false;
}
//删除用户的离线消息
bool OfflineMsgModel::deleteMsg(int userid){
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "delete from OfflineMessage where userid = %d",
            userid
            );

    // 从连接池中获取一个mysql连接
    ConnectionPool *sqlConnPool = ConnectionPool::getConnectionPool();
    auto sqlConn = sqlConnPool->getConnection();

    // 执行操作
    bool state = sqlConn->update(sql);
    if (state)
    {
        sqlConn->update(sql);
        return true;
    }
    return false;
}
//查询用户的离线消息
vector<string> OfflineMsgModel::queryMsg(int userid){
    // 组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "select message from OfflineMessage where userid = %d",
            userid
            );

    // 从连接池中获取一个mysql连接
    ConnectionPool *sqlConnPool = ConnectionPool::getConnectionPool();
    auto sqlConn = sqlConnPool->getConnection();

    // 执行操作
    vector<string> vec;
    MYSQL_RES* res = sqlConn->query(sql);
    if(res != nullptr){
        MYSQL_ROW row;
        while((row = mysql_fetch_row(res)) != nullptr){
            vec.emplace_back(row[0]);
        }
    }
    mysql_free_result(res);
    return vec;
}